const getFindDeep = require('deepdash/getFindDeep');

const lodash = require('lodash/lodash');
const isEmpty = require('lodash/isEmpty');
const compact = require('lodash/compact');
const intersectionBy = require('lodash/intersectionBy');
const treeData = require('./treeData');

const findDeep = getFindDeep(lodash);

function findCommonAncestor(treeData, nodes, propMap = defaultItemPropMap) {
  // 少于两个节点对比，无意义
  if (isEmpty(nodes) || nodes.length < 2) return undefined;
  const metaSet = nodes.map((item) =>
    findDeep(
      treeData,
      (node) => {
        const nodeValue = node[propMap.keyProp];
        if (nodeValue === item[propMap.keyProp]) return true;
      },
      propMap.deepdashOptions
    )
  );

  // 移除没有找到的节点; 排序把层级最深的node放在第一位
  const descendOrderedMeta = compact(metaSet).sort((meta1, meta2) => {
    // @ts-ignore
    return meta2.context.depth - meta1.context.depth;
  });

  const descendOrderedParents = descendOrderedMeta.map(
    (item) => item.context.parents
  );

  // 至少需要两个节点的父元素集合进行对比，否则无意义
  if (descendOrderedParents.length < 2) return undefined;
  const theMostParents = descendOrderedParents.shift();

  return intersectionBy(
    theMostParents,
    ...descendOrderedParents,
    `value.${propMap.keyProp}`
  );
}

function findLatestCommonAncestor(
  treeData,
  nodes,
  propMap = defaultItemPropMap
) {
  const latestAncestor = findCommonAncestor(treeData, nodes, propMap).pop()

  return latestAncestor ? latestAncestor.value : undefined; // 因为祖先节点，从上到下，最近的就是最后一个元素
}

const nodes = [
  {
    name: 'level5',
    value: 50,
    children: [],
  },
  {
    name: 'level47',
    value: 47,
  },
  {
    name: 'level43',
    value: 43,
  },
];

const propMap = {
  keyProp: 'value',
  childrenProp: 'children',
  deepdashOptions: {
    childrenPath: ['children'],
  },
};
const result = findLatestCommonAncestor(treeData, nodes, propMap);

console.log(`node ${nodes[0].name} 和 ${nodes[1].name}的共同祖先：\n`, result);
